package cx.hoffmann.bab.container;

/**
 * Created by IntelliJ IDEA.
 * User: lasombra
 * Date: 2009/09/30
 * Time: 7:34:48 PM
 */

import org.mortbay.jetty.runner.Runner;

import java.io.*;
import static java.lang.System.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class Main
{
	private static final String WAR_POSTFIX = ".war";
	private static final String WAR_NAME = "bab";
	private static final String WAR_FILENAME = WAR_NAME + WAR_POSTFIX;
	private static final int KB = 1024;

	private Main()
	{
	}

	public static void main( String[] args ) throws Exception
	{
		out.println( "Welcome to the Borrow a Book Project." );
		out.println( "This is a standalone web server. All the project is self-contained." );
		out.println( "To quit this application, press Ctrl+C" );

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		URL resource = classLoader.getResource( WAR_FILENAME );

		if( resource == null )
		{
			err.println( "Could not find the " + WAR_FILENAME + " on classpath!" );
			exit( 1 );
		}

		File warFile = File.createTempFile( WAR_NAME + "-", WAR_POSTFIX );
		out.println( "Extracting " + WAR_FILENAME + " to " + warFile + " ..." );

		writeStreamTo( resource.openStream(), new FileOutputStream( warFile ), 8 * KB );

		out.println( "Extracted " + WAR_FILENAME );
		out.println( "Launching Jetty Runner..." );

		List<String> argsList = new ArrayList<String>();
		if( args != null )
		{
			argsList.addAll( Arrays.asList( args ) );
		}
		argsList.add( warFile.getCanonicalPath() );
		Runner.main( argsList.toArray( new String[argsList.size()] ) );
		exit( 0 );
	}

	public static int writeStreamTo( final InputStream input, final OutputStream output,
									 int bufferSize ) throws IOException
	{
		int available = Math.min( input.available(), 256 * KB );
		byte[] buffer = new byte[Math.max( bufferSize, available )];
		int answer = 0;
		int count = input.read( buffer );
		while( count >= 0 )
		{
			output.write( buffer, 0, count );
			answer += count;
			count = input.read( buffer );
		}
		return answer;
	}
}